import 'dart:collection';

import 'package:duo_zui/Util/config_color.dart';
import 'package:duo_zui/constant/cache_key.dart';
import 'package:duo_zui/constant/constant.dart';
import 'package:duo_zui/like_button/like_button.dart';
import 'package:duo_zui/widget/BaseModuleWidget.dart';
import 'package:flutter/material.dart';
import 'package:duo_zui/model/model.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:async';
import 'dart:math' as math;
import 'package:dio/dio.dart';
import 'package:duo_zui/router.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:duo_zui/widget/SwiperWidget.dart';
import 'package:duo_zui/tool/WidgetUtils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../router.dart';

class News extends StatefulWidget {
  @override
  String url;
  News({Key key, @required this.url}) : super(key: key);
  _NewsState createState() => _NewsState();
}

class _NewsState extends State<News> with AutomaticKeepAliveClientMixin{
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
      url = widget.url;
      getData();
  }

  bool isbottem = false;

  String url;
  dynamic lastKey = 0;
  List<dynamic> dataList = [];

  void getData()async{
    if (lastKey == '-1'){
      dataList = [];//下拉刷新的时候将DataList制空
    }

    Dio dio = new Dio();
    print("$url$lastKey");
    Response response = await dio.get("$url$lastKey");
    Reslut reslut = Reslut.fromJson(response.data);
    if(!reslut.response.hasMore){
      setState(() {
        isbottem = true;
      });//如果没有数据就不继续了
      return;
    }
    lastKey = reslut.response.lastKey;//更新lastkey
    setState(() {
      List<dynamic> data = [];
      data.addAll(reslut.response.feeds);
      dataList.addAll(data);//给数据源赋值
    });
  }

  _getListCount() {
      ///如果有数据,最上面是轮播图最下面是加载loading动画，需要对列表数据总数+2
      return (dataList.length > 0) ? dataList.length + 2 : dataList.length + 1;
    }

  _onScrollNotification(ScrollNotification scrollInfo) {
    if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) {
      //滑到了底部
      getData();
    }
  }

  Future<void> _handleRefresh() {
    final Completer<void> completer = Completer<void>();
    Timer(const Duration(seconds: 1), () {
      completer.complete();
    });
    return completer.future.then<void>((_) {
      lastKey = '-1';
      getData();
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return getContentSliver(context, dataList);
  }

  getContentSliver(BuildContext context, List<dynamic> dataList) {

    print('getContentSliver');
    if (dataList == null || dataList.length == 0) {
      return Text('暂无数据');
    }
    return SafeArea(
      top: false,
      bottom: false,
      child: Builder(

        // This Builder is needed to provide a BuildContext that is "inside"
        // the NestedScrollView, so that sliverOverlapAbsorberHandleFor() can
        // find the NestedScrollView.
        builder: (BuildContext context) {
          return  NotificationListener<ScrollNotification>(
              child: CustomScrollView(
                physics: const BouncingScrollPhysics(),
                key: PageStorageKey<String>("我的"),
                slivers: <Widget>[
                  SliverOverlapInjector(
                    // This is the flip side of the SliverOverlapAbsorber above.
                    handle:
                    NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                  ),
                  SliverList(
                      delegate: SliverChildBuilderDelegate(
                          ((BuildContext context, int index) {
                            print("${dataList.length} $index");
                            if(index < dataList.length) {
                              return AppImageRight(context, dataList, index);
                            }else{
                              if(isbottem){
                                 return Align(
                                   alignment: Alignment.center,
                                   child: Text('已经到底了',style: TextStyle(fontSize: 13.0, color: ConfigColor.colorText2,decoration: TextDecoration.none)),
                                 );
                              }else{
                                return _buildProgressIndicator();
                              }
                            }
                          }),
                          childCount: dataList.length + 1)

                  ),
                ],
              ),
            onNotification: (ScrollNotification scrollInfo) =>
                _onScrollNotification(scrollInfo),
          );
        },
      ),
    );
  }


  @override void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}
///上拉加载更多
Widget _buildProgressIndicator() {
  ///是否需要显示上拉加载更多的loading
  Widget bottomWidget = new Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
    ///loading框
    new SpinKitThreeBounce(color: Color(0xFF24292E)),
    new Container(
      width: 5.0,
    ),
  ]);
  return new Padding(
    padding: const EdgeInsets.all(20.0),
    child: new Center(
      child: bottomWidget,
    ),
  );
}

Widget AppImageRight(BuildContext context,List<dynamic> feeds, int index){
  Feed feed = feeds[index];
  return Container(
      decoration: BoxDecoration(
      color: ConfigColor.colorContentBackground,
      border: BorderDirectional(
      bottom: BorderSide(color: ConfigColor.colorDivider, width: 10))),
    child: Column(
      children: <Widget>[
        Container(
          height: 70,
          child: ActivityTitleWidget(context, feed.post.user.photo, feed.post.user.nickname, feed.post.category == null ? '' : feed.post.category.title),
        ),
      GestureDetector(
        onTap: () {
          int id = feed.post.id;
          String url = 'http://www.appshuo.club/appview/p/';
          MyRouter.push(context, MyRouter.articelPage,{'url': '$url$id','article': feed.post});
        },
        child: Container(
          child: Row(
            children: <Widget>[
              Container(
                width: MediaQuery.of(context).size.width - 120,
                height: 120,
                margin: EdgeInsets.all(0),
                child: Column(
                  children: <Widget>[
                    Container(
                      child: TitleLabel(context, feed.post.title),
                      //height: 90,
                      padding: const EdgeInsets.fromLTRB(10, 0, 10, 5),
                      alignment: Alignment.topLeft,
                    ),
                    Expanded(
                      child: Container(
                          padding: EdgeInsets.fromLTRB(10, 0, 10, 5),
                          alignment: Alignment.topLeft,
                          child: DescriptionLabel(context, feed.post.description == null ? '' : feed.post.description)
                      ),
                    )
                  ],
                ),
              ),
              Expanded(
                child:  Container(
                  margin: EdgeInsets.only(left: 0),
                  // width: 120,
                  // height: 120,
                  alignment: Alignment.topCenter,
                  child: Image.network(feed.image,width: 120,height: 120,),
                ),
              ),
            ],
          ),
        )),
        Container(
          child: ListBottomWidget(context, feed.post),
          margin: EdgeInsets.fromLTRB(15, 0, 0, 5),
        )
      ],
    ));
}

Widget ListBottomWidget(BuildContext context,Post post){
  return Row(
    children: <Widget>[
      //IconText(context, post.praiseCount==0?'赞':post.praiseCount, Constant.ASSETS_IMG + 'ic_vote.png',),
      LikeButton(
          size: 25.0,
          id: post.id,
          isLiked: post.likeFlag,
          likeCount: post.praiseCount==0 ? 0 : post.praiseCount,
          likeBuilder: (bool isLiked) {
            return Image.asset(Constant.ASSETS_IMG + 'ic_vote.png',fit: BoxFit.fitWidth,width: 25,height: 25,color: isLiked ? Colors.green : Colors.grey);
          },
          //key: _globalKey,
          countBuilder: (int count, bool isLiked, String text) {
            final ColorSwatch<int> color =
            isLiked ? Colors.pinkAccent : Colors.grey;
            Widget result;
            if (count == 0) {
              result = Text(
                '赞',
                style: TextStyle(
                  fontSize: 12,
                  color: color,
                  decoration: TextDecoration.none
                 ),
              );
            } else
              result = Text(
                count >= 1000
                    ? (count / 1000.0).toStringAsFixed(1) + 'k'
                    : text,
                style: TextStyle(
                  fontSize: 12,
                  color: color,
                  decoration: TextDecoration.none
                 ),
              );
            return result;
          },
          likeCountPadding: const EdgeInsets.only(left: 5.0),
          onTap: (bool isLiked)
          {
            return onLikeButtonTap(isLiked, post);
          }
      ),
      Padding(padding: EdgeInsets.only(left: 20),),
      IconText(context, post.commentCount==0?'评论':post.commentCount, Constant.ASSETS_IMG +
          'ic_notification_tv_calendar_comments.png'),
    ],
  );
}

Future<bool> onLikeButtonTap(bool isLiked, Post item) {
  ///send your request here
  final Completer<bool> completer = new Completer<bool>();
  _islogin(item.id,completer,item,isLiked);
  return completer.future;
}

_addLike(id,isLiked) async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  Dio dio = new Dio();
  String url = 'http://www.appshuo.club/api/client/api/article/applaud/${id}';
  Map<String, String> headers = new HashMap();
  headers['Content-Type'] = 'application/json';
  headers['accessToken'] = prefs.get(CacheKey.USE_NET_DATA);
  Options option;
  if(!isLiked){
    option = new Options(method: "post");
  }else{
    option = new Options(method: "delete");
  }
  option.headers = headers;
  Response response = await dio.request(url, data: {}, options: option);
  Reslut reslut = Reslut.fromJson(response.data);
}

_islogin (id,completer,item,isLiked) async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  if(prefs.getBool(CacheKey.USER_IS_LOGIN)?? false){
    _addLike(id, isLiked);
    Timer(const Duration(milliseconds: 200), () {
      item.likeFlag = !item.likeFlag;
      item.praiseCount =
      item.likeFlag ? item.praiseCount + 1 : item.praiseCount - 1;
      // if your request is failed,return null,
      completer.complete(item.likeFlag);
    });
  } else{
    Fluttertoast.showToast(msg: "请先登录");
  }
}

Widget ActivityTitleWidget(BuildContext context,String iconString,String title,String category){
  return Row(
    children: <Widget>[
      Container(
        margin: EdgeInsets.fromLTRB(12, 2, 10, 0 ),
        child: CircleAvatar(
          backgroundImage: NetworkImage(iconString),
          radius: 17.0,
        ),
      ),
      Container(
        margin: EdgeInsets.fromLTRB(5, 2, 10, 0 ),
        child: TitleLabel(context, title),
      ),
      Expanded(
        child: Container(
          padding: EdgeInsets.fromLTRB(10, 1, 10, 0),
          alignment: Alignment.centerRight,
          //child: Image.asset('toolbarShare.png',width: 18,height: 18,),
          child: TitleLabel(context, category),
        ),
      )
    ],
  );
}